package team13;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;

public class GraphHolder {
	private Graph<Node, Edge> graph;
	private Node[] nodeArray;
	private RoleFinder roleFinder;
	
	public void start(String arg){
		initGraph();
		System.out.println("graph size: " + graph.getVertexCount());
		initNodeArray();
		
		//Part A
		roleFinder = new RoleFinder(this);
		roleFinder.findRole(Integer.parseInt(arg));
		
		/*
		System.out.println("start writing role result");
		writeRoleResult();
		System.out.println("finish writing role result");
		*/
		
		//Part B
		
	}
	
	public Graph<Node, Edge> getGraph(){
		return graph;
	}
	
	public Node[] getNodeArray(){
		return nodeArray;
	}
	
	private void initNodeArray(){
		nodeArray = new Node[graph.getVertexCount()];
		for(Node node: graph.getVertices()){
			nodeArray[node.getId()] = node;
		}
	}
	
	private void initGraph(){
		graph = new UndirectedSparseGraph<Node, Edge>(); //input is unDirected Graph
		
		try {
			//parse graph
			BufferedReader in = new BufferedReader(new FileReader("hw3.masklink_1029.txt"));
			String line = null;
			HashMap<String, Node> nodeMap = new HashMap<String, Node>();
			while((line = in.readLine()) != null){
				String[] nodeStr = line.split("\t");
				Node node0 = null, node1 = null;
				if(nodeMap.containsKey(nodeStr[0])){
					node0 = nodeMap.get(nodeStr[0]);
				}else{
					node0 = new Node(nodeStr[0]);
					nodeMap.put(nodeStr[0], node0);
				}
				if(nodeMap.containsKey(nodeStr[1])){
					node1 = nodeMap.get(nodeStr[1]);
				}else{
					node1 = new Node(nodeStr[1]);
					nodeMap.put(nodeStr[1], node1);
				}
				graph.addEdge(new Edge(), node0, node1);
			}
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void writeRoleResult(){
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter("TEAM-13_A.txt"));
			ArrayList<ArrayList<Integer>> clusterList = roleFinder.getClusterList();
			for(int i = 0; i < clusterList.size(); i++){
				System.out.println("cluster: " + i + " size: " + clusterList.get(i).size());
				for(int j = 0; j < clusterList.get(i).size(); j++){
					out.write(clusterList.get(i).get(j) + " ");
				}
				out.newLine();
			}
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
